var sqlDebug = 0;
var q_select_condition = null;
var requestUrl = "";
var menuCode = "";
var q_condition = null;
var rownumberer = true;
var conditionItems = new Array();
var tablePanelItems = new Array();
var deep = 1;
var url={};
var urlType={};
var urlParam=new Array();
var url_field = {};
var is_openrun = 0;
var is_button = 1;
var exportLevel = 1;
var qidList = new Array();
var querySql = {};
var deepMap = {};
var titleMap = {};
var sheetNameMap = {};
var printMap = {};
var upFlag=true;
var orderCheck = 100000;
var stripeRows = true;// 是否显示斑马线
var tablesIsCover = null;
var sortableColumns = true;
var isLocalStorage = true;
var enableLocking = true;
// 级联组件初始化赋值数组
var relationConditionArr = [];
// 表格表头的层级
var tableHeaderMap={}
var tableHeaderRowsNum=1;


/**
 * 初始化套表
 *
 * @param tables_id
 * @param q_condition
 * @param closeHidden
 * @returns
 */
function initReportQueryTablesPanel(tables_id, q_condition) {
	loadReport(tables_id,q_condition);
	var tablesPanel = initTablesPanel();

	// 根据查询结果控制按钮是否显示
	if(is_button == 1){
		if(Ext.ComponentQuery.query('button[name="screen"]')[0]){
    	Ext.ComponentQuery.query('button[name="screen"]')[0].setHidden(false);
		}
	}else{
		if(Ext.ComponentQuery.query('button[name="screen"]')[0]){
    	Ext.ComponentQuery.query('button[name="screen"]')[0].setHidden(true);
	}
	}

	// 根据查询结果控制是否允许导出
    if(exportLevel == 0){
    	Ext.ComponentQuery.query('button[name="export"]')[0].setHidden(true);
    	Ext.ComponentQuery.query('button[name="print"]')[0].setHidden(true);
    }else{
    	Ext.ComponentQuery.query('button[name="export"]')[0].setHidden(false);
    	Ext.ComponentQuery.query('button[name="print"]')[0].setHidden(false);
    }

    if(is_openrun == 1){
    	reloadStore();
    }
	return tablesPanel;
}

/**
 * 加载配置信息
 *
 * @param code
 * @param q_condition
 */
function loadReport(tables_id,q_condition) {
	Ext.Ajax.request({
		method : 'POST',
		url : "/sys-report/getReportQueryTablesData",
		params : {
			tables_id : tables_id
		},
		async : false,
		success : function(response, options) {
			// 获取返回的JSON，并根据gridid，获取表头配置信息
			var respText = Ext.util.JSON.decode(response.responseText);
			is_openrun = respText.isOpenrun;
			is_button = respText.isButton;
			exportLevel = respText.exportLevel;
			var conditionList = eval(respText.conditionList);
			conditionConf(conditionList,q_condition);
			var tablesList = eval(respText.tablesList);
			tablePanelConf(tablesList);
			qidList = eval(respText.qidList);
		},
		failure : function(response, options) {
			Ext.MessageBox.minWidth = 120;
			Ext.Msg.alert('提示', '获取报表配置信息失败！');
		}
	});
}


/**
 * 初始化套表panel
 *
 * @returns {Ext.panel.Panel}
 */
function initTablesPanel(){
    var panel=  new Ext.panel.Panel ({
	    itemId:'reportQueryTablesPanel',
		name:"reportQueryTablesPanel",
	    layout: {
            type: 'vbox',
            align: 'stretch',
            flex: 1
        },
        height:'100%',
        width:'100%',
        border: false,
        dockedItems: [
            {
                xtype: 'toolbar',
                dock: 'top',
                itemId: 'contentPanel_toolbar',
                items: items
            }
        ],
        items: [
            initSelect(),
            initTabPanel()
        ]
	});
    return panel;
}

/**
 * 初始化条件区域
 */
function initSelect() {
	var formPanel = new Ext.form.Panel({
	    width:'100%',
	    itemId:'condition',
	 	autoScroll: true,
	 	maxHeight : 150,// 查询区显示4行
	 	minHeight : 0,
	 	layout:'column',
	    border: false,
	    frame: false,
	    defaults:{
	    	labelAlign: "right",
	        xtype:"textfield",
	        labelWidth: 100,
		    flex: 1,
		    columnWidth:0.32,
	        margin:1
	     },
	   items: conditionItems
	});
    return formPanel;
}

/**
 * 初始化标签页
 *
 * @returns
 */
function initTabPanel() {

	var tabPanel = Ext.create('Ext.tab.Panel', {
		// anchor : '100% -17',
		// border : true,
		flex: 8,
		border: true,
		// cls:"ui-tab-bar",
    	// bodyCls:"ui-tab-body",
		tabPosition : "bottom",
		itemId :'reportQueryTabPanel',
		plain: true,
		tabBar : {
			height : 24,
			defaults : {
				height : 22
			}
		},
		items : tablePanelItems
	});
	return tabPanel;
}


var items = [
	{
	xtype: 'button',
	text: '查询',
	itemId: 'report_query_search',
	icon: '/report/image/sysbutton/search.png',
	handler: function (btn) {
		reloadStore();
	}
},{
	xtype: 'button',
	text: '导出',
	name: 'export',
	disabled: true,
	icon: '/report/image/sysbutton/export.png',
	handler: function (btn) {
		//btn.setDisabled(true);
		//弹出进度框
		progressShow();
		var paramList = new Array();
		if(!isNull(tablesIsCover)){
			for (var i = 0; i < tablesIsCover.length; i++ ){
				var formData = getConditionValues();
				// formData = $.extend({}, formData, form.getValues());
				formData.tables_id = tables_id;
				paramList.push(formData);
			}
		}
		for ( var i = 0; i < qidList.length; i++) {
			var config_grid = DSYWidget.Manager.grid['reportQueryGrid'+qidList[i]].config;
			var unitPanel = Ext.ComponentQuery.query('combobox[name="unitSelect' + qidList[i] + '"]')[0];
			var unit_name = "";
			if(unitPanel){
				unitValue = unitPanel.getValue();
				if(unitValue == 100000000){
					unit_name = "亿元";
				}else if(unitValue == 10000){
					unit_name = "万元";
				}else if(unitValue == 1){
					unit_name = "元";
				}
				unit_name="单位："+unit_name;
			}
			config_grid.exportExcel = $.extend(config_grid.exportExcel, {
				exportExcel: true,
				param: {
					deep:deepMap[qidList[i]],
					title:titleMap[qidList[i]],
					sheetName:sheetNameMap[qidList[i]],
					unit_name:unit_name
				}
			});
			var exportExcel = config_grid.exportExcel;
			exportExcel = DSYGrid.exportExcelConfig('reportQueryGrid'+qidList[i], config_grid);
			var param = $.extend(exportExcel.param, DSYGrid.getGrid('reportQueryGrid'+qidList[i]).getStore().getProxy().extraParams);
			var arr=classNameArray.filter(function (item,index) {
				return item.Q_ID==qidList[i]
			})
			param.className=arr[0]?arr[0].CLASSNAME:"";
			param.Q_REMARK=arr[0]?arr[0].Q_REMARK:"";
			param.Q_NOTE=arr[0]?arr[0].Q_NOTE:"";
			param.export_data_format=arr[0]?arr[0].EXPORT_DATA_FORMAT:"";
			param.config = Ext.JSON.encode(exportExcel.config);
			var sorter = DSYGrid.getGrid('reportQueryGrid'+qidList[i]).getStore().getSorters().items[0];
			if(sorter){
				param = $.extend({}, param, {
					sort: sorter.config.property,
					dir: sorter.config.direction
				});
			}
			paramList.push(param);
		}
		tablesIsCover: isNull(tablesIsCover) ? false : true
		// 导出Excel：使用虚拟表单提交
		if (!$('form#download') || $('form#download').length <= 0) {
			$('<form id="download"></form> ').appendTo(document.body);
		}
		var array = [];
		if(!isNull(tablesIsCover)){
			for(var i = 0; i < tablesIsCover.length; i++) {
				array.push({"type":tablesIsCover[i].type,"title":tablesIsCover[i].title});
			}
		}
		var params={
				exportconfig: encode64(Ext.JSON.encode(paramList)),
				tablesIsCover: encode64(JSON.stringify(array))
		}
		downloadPublicFiles('/sys-report/exportTables', 'POST', params).then(function (data) {
			try {
				if (!data.contentDisposition) {
					var msg = !!data.errMessage ? data.errMessage : '导出失败！';
					//后台返回的空格变成+号，替换回来
					msg = msg.replace(/\+/g, ' ');
					setTimeout(function () {
						Ext.Msg.alert('提示', msg);
					}, 1000);
				}
			} catch (e) {
			}
		}).catch(function (error) {
			Ext.Msg.alert('提示', '导出失败！');
		});
		// Ext.Ajax.request({
		// 	url: '/report/sys-manage/exportTables',
		// 	isUpload: true,
		// 	form: 'download',
		// 	useDefaultXhrHeader: true,
		// 	params: {
		// 		exportconfig: encode64(Ext.JSON.encode(paramList)),
		// 		tablesIsCover: encode64(JSON.stringify(array))
		// 	}
		// });
	}
},{
	xtype:'button',
	text:'打印',
	name:'print',
	disabled: true,
	icon: '/report/image/sysbutton/print.png',
	handler:function(){
		var form = Ext.ComponentQuery.query('form#condition')[0];
 		var data = form.getValues();
 		var paramList = new Array();
 		if(!isNull(tablesIsCover)){
    		var formData = getConditionValues();
            formData.tables_id = tables_id;
            paramList.push(formData);
    	}
 		for ( var i = 0; i < qidList.length; i++) {
 			var param = Ext.clone(data);
 			param["q_id"] = qidList[i];
 			param["tables_id"] = tables_id;
 			param["condition"]=q_select_condition;
 			param["rownumberer"] = rownumberer;
 			param["tableTitle"] = titleMap[qidList[i]];
 			var unitPanel = Ext.ComponentQuery.query('combobox[name="unitSelect' + qidList[i] + '"]')[0];
 	    	var unitValue = 1;
 	    	var unit_name = "";
 	    	if(unitPanel){
				unitValue = unitPanel.getValue();
 	    		param["unit"] = unitValue;
            	if(unitValue == 100000000){
         	  	  	unit_name = "亿元";
         	    }else if(unitValue == 10000){
         	    	unit_name = "万元";
         	    }else if(unitValue == 1){
         	    	unit_name = "元";
         	    }
            	unit_name="金额单位："+unit_name;
 	    	}
     		param["tableUnit"] = unit_name;
     		var headerLeft = "";
            var headerCenter = "";
            var headerRight = "";
            var footerLeft = "";
            var footerCenter = "";
            var footerRight = "";
     		if(i == 0){
                var printConfig = printMap[qidList[i]];
                if(printConfig){
                	var tempPrint = printConfig.split('#');
                	if(tempPrint.length >= 2){
                		var printFooter = tempPrint[1];
                		var tempPrintFooter = printFooter.split('-');
                		footerLeft = tempPrintFooter[0];
                    	if(tempPrintFooter.length >=2){
                    		footerCenter = tempPrintFooter[1];
                    	}

                    	if(tempPrintFooter.length >=3){
                    		footerRight = tempPrintFooter[2];
                    	}
                	}
                	var printHeader = tempPrint[0];
                	var tempPrintHeader = printHeader.split('-');
                	headerLeft = tempPrintHeader[0];
                	if(tempPrintHeader.length >=2){
                		headerCenter = tempPrintHeader[1];
                	}

                	if(tempPrintHeader.length >=3){
                		headerRight = tempPrintHeader[2];
                	}
                }
     		}
     		var printSet = [{
 				header_left : headerLeft,
     			header_center : headerCenter,
     			header_right : headerRight,
     			footer_left : footerLeft,
     			footer_center : footerCenter,
     			footer_right : footerRight
     		}];
     		param["printSet"] = Ext.util.JSON.encode(printSet);
     		param["gridColumns"]=Ext.util.JSON.encode(DSYGrid.getGrid('reportQueryGrid'+qidList[i]).headerConfig.headerJson);
     		var sorter = DSYGrid.getGrid('reportQueryGrid'+qidList[i]).getStore().getSorters().items[0];
      	    if(sorter){
      	    	param["sort"] = sorter.config.property;
      	    	param["dir"] = sorter.config.direction;
      	    }
 			paramList.push(param);
 		}
 		// var temp_form = document.createElement("form");
 		// temp_form.action = "/report/sys-manage/printTables";
 		// temp_form.target = "_blank";
 		// temp_form.method = "post";
 		// temp_form.style.display = "none";
 		// var opt = document.createElement("textarea");
		// opt.name = "printconfig";
		// opt.value = encode64(Ext.util.JSON.encode(paramList));
		// temp_form.appendChild(opt);
		// var opt1 = document.createElement("textarea");
		// opt1.name = "tablesIsCover";
		// opt1.value = null;
		// var array = [];
		// if(!isNull(tablesIsCover)){
		// 	for(var i = 0; i < tablesIsCover.length; i++) {
		// 		array.push(tablesIsCover[i].type);
		// 	}
		// }
		// opt1.value= array;
		// temp_form.appendChild(opt1);
 		// document.body.appendChild(temp_form);
 		// temp_form.submit();
		 var array = [];
		 var paramList = encode64(Ext.util.JSON.encode(paramList));
		 if(!isNull(tablesIsCover)){
			 for(var i = 0; i < tablesIsCover.length; i++) {
				 array.push(tablesIsCover[i].type);
			 }
		 }
		 let printParams={
			printconfig:paramList,
			tablesIsCover:array.join(",")
		 }
		var mask = new Ext.LoadMask({
			msg: 'Loading...', // 加载中的提示信息
			target: Ext.ComponentQuery.query('panel[name="reportQueryTablesPanel"]')[0]// 要添加遮罩层的元素的ID
		});
		// mask.show()
		printPublicFiles("/sys-report/printTables","POST",printParams,"").then(function(){
			// mask.hide();
		})
	}
},'->',
initButton_Screen()];

function progressShow() {
	Ext.MessageBox.show({
		title : '请耐心等待...',
		progressText : '正在导出...',
		width : 400,
		progress : true,
		closable : false,
		animateTarget : '导出',
		msg : '请稍等......'
	});

	var exportCount = 0;
	var schedules = 0;

	//异步请求是否反馈标识
	var flag = true;
	var fn = function() {
		return function(){
			Ext.Ajax.request({
				method: 'GET',
				url: "/sys-report/exportSchedule",
				async: true,
				success: function (response) {
					var respText = Ext.util.JSON.decode(response.responseText);
					schedules = respText.schedules == null ? -1: respText.schedules;
					exportCount = respText.exportCount == null ? -1: respText.exportCount;
					//当exportIsEnd等于1时,套表导出已完成,将flag标识设置为false
					if (respText.exportIsEnd == "1"){
                        flag = false;
                    }
					sheetName = respText.sheetName;
				},
				failure: function () {
					Ext.MessageBox.minWidth = 120;
					Ext.Msg.alert('提示', '获取信息失败！');
				}
			});
			//当exportCount大于等于1时,异步请求已反馈并且count有值,flag为true,目前还未得到有效反馈
			if (exportCount >= 1 && flag){
				flag = false;
			}
			if (flag){
				//异步请求未反馈
				Ext.MessageBox.updateProgress(0, "已完成 0 %", "正在导出...");
			}else {
				//异步请求已反馈
				if (exportCount == -1 || exportCount == 0) {
					Ext.MessageBox.close();
					clearInterval(getSchedule);
					return;
				}
				Ext.MessageBox.updateProgress(schedules / exportCount, "已完成 "+Math.round(100 * (schedules / exportCount)) + ' %', '正在导出   ' + sheetName);
			}
		}
	};
	var getSchedule = setInterval(fn(),500);
}

/**
 * 全屏隐藏参数
 *
 * @returns {___anonymous4492_4885}
 */
function initButton_Screen() {
        return {
            xtype: 'button',
            text: '全屏',
            name: 'screen',
            icon: '/report/image/sysbutton/fullscreen.png',
            handler: function () {
				var url = requestUrl+"?";
				for(var key in q_condition){
					url = url + "&"+key+"="+q_condition[key];
					}
				url = url + "&condition="+q_select_condition;
				urlSplit(url);
            }
        };
    }

/**
 * 条件配置
 *
 * @param condition
 * @param q_condition
 * @returns {Array}
 */
function conditionConf(condition,q_condition) {
	if (condition != null && condition.length > 0) {
		Ext.Array.forEach(condition, function(str) { // 单纯的遍历数组
			var cId = str.C_ID;
			var model = str.C_DATA_MODEL;
			var source = str.C_DATA_SOURCE;
			var value = str.C_DATA_VALUE;
			var dispmode = str.C_DISP_MODE;
			var fieldcode = str.C_CODE;
			var fieldtitle = str.C_TITLE;
			var tips = str.C_TIPS;
			var ismust = str.IS_MUST_INPUT;
			var ismul = str.IS_MUL;
			var srccode = str.C_SRC_ID;
			var conditionIsRight = str.IS_RIGHT;
			var hiddenFlag = false;
			var isShow = str.IS_SHOW;
			var isLeaf = str.IS_LEAF;
			var isRootShow = str.IS_ROOT_SHOW;
			var isDependentFlag = false;// 是否有依赖，默认没有依赖
			// 是否有级联关系
			if (srccode) {
				isDependentFlag = true;
				//关联条件有多个的处理
				var srcCodeList = srccode.split(",");
				// 如果当前组件有级联关系,添加进数组,后续统一进行赋值处理
				for (var i = 0; i < condition.length; i++) {
					for (var j = 0; j < srcCodeList.length; j++) {
						var srcCode = srcCodeList[j];
						if (condition[i].C_CODE === srcCode) {
							var valueCondition = condition[i].C_DATA_VALUE;
							if (!isNull(q_condition[srcCode])){
								valueCondition = q_condition[srcCode];
							}
							relationConditionArr.push({
								name: srcCode,
								xtype: condition[i].C_DISP_MODE,
								value: valueCondition
							});
						}
					}
				}
			}
			for ( var key in q_condition) {
				if (fieldcode.toUpperCase() == key.toUpperCase()) {
					value = q_condition[key].toString();
				}
			}
			if (isShow == 0) {
				hiddenFlag = true;
			}
			if ('treecombobox' == dispmode) {
				conditionItems.push({
					xtype : 'treecombobox',
					fieldLabel : fieldtitle,
					name : fieldcode,
					maxPickerHeight : 270,
					displayField : 'name',
					valueField : 'id',
					rootVisible : isRootShow == "1" ? true : false,
					lines : false,
					selectModel : getLeafFlag(isLeaf),
					checkModel : getMulFlag(ismul),
					multiSelect : true,
					value : value,
					hidden : hiddenFlag,
					srccode : srccode,
					isRight : conditionIsRight,
					margin : '2 5 2 6',
					padding : '0 0 0 0',
					editable : false,
					allowBlank : isMustPut(ismust),
					emptyText : !!value ? "" : tips,
					rootUse : getRootFlag(ismul),
					store : DebtQueryTreeStore(cId, {
						isRight : conditionIsRight,
						isMul : ismul,
						isDependent : isDependentFlag
					}, ismul),
					listeners : {
						change : function(self, newValue) {
							var conditionPanel = Ext.ComponentQuery.query('form#condition')[0];
							conditionPanel.items.each(function(item, index, length) {
								if (item.srccode && item.name != self.name) {
									var srcFlag = false;
									var srcIds = item.srccode.split(',');
									for ( var i = 0; i < srcIds.length; i++) {
										if (self.name.trim() == srcIds[i].trim()) {
											srcFlag = true;
											break;
										}
									}
									if (srcFlag) {
										var xtype = item.xtype;
										var name = item.name;
										var target = Ext.ComponentQuery.query(xtype + '[name="' + name + '"]')[0];
										var targetValue = item.value;
										var linkValue = self.value;
										if (xtype == "treecombobox" || xtype == "combobox") {
											target.getStore().getProxy().extraParams[self.name.trim()] = linkValue;
											target.getStore().load({
												callback : function(records, operation, success) {
													if(records.length == 1){
	            			    			    		if (xtype == "treecombobox") {
															if(records[0].childNodes && records[0].childNodes.length > 0){
																target.setValue('');
															}else{
																target.setValue(records[0].get("code"));
															}
														}else{
															target.setValue(records[0].get("code"));
														}
	            			    			    	}else{
	            			    			    		if(xtype == "treecombobox"){
		            			    			    		//target.setValue('');
		            			    			    	}else{
		            			    			    		var dataFlag = false;
			            			    			    	for(var i=0;i<records.length;i++){
			            			    			    		var code = records[i].get("code");
			            			    			    		if(code == targetValue){
			            			    			    			dataFlag = true;
			            			    			    			break;
			            			    			    		}
			            			    			    	}
			            			    			    	if(dataFlag){
			            			    			    		target.setValue(targetValue);
			            			    			    	}else{
			            			    			    		target.setValue('');
			            			    			    	}
		            			    			    	}
	            			    			    	}
												}
											});
										} else if (xtype == "textfield") {
											target.setValue('');
											if (linkValue) {
												$.post('/getTextFieldValue', {
													q_id : tables_id,
													c_code : item.name,
													target : self.name.trim() + "#" + linkValue,
												}, function(data) {
													if (data.targetValue) {
														target.setValue(data.targetValue);
													}
												}, 'JSON');
											}
										}
									}
								}
							});
						}
					}
				});
			} else if ('combobox' == dispmode) {
				conditionItems.push({
					xtype : "combobox",
					fieldLabel : fieldtitle,
					name : fieldcode,
					store : comboboxStore(model, cId, conditionIsRight, source),
					queryMode : 'local',
					value : value,
					hidden : hiddenFlag,
					srccode : srccode,
					isRight : conditionIsRight,
					displayField : 'name',
					valueField : 'code',
					margin : '2 5 2 6',
					padding : '0 0 0 0',
					emptyText : !!value ? "" : tips,
					allowBlank : isMustPut(ismust),
					editable : false,// 禁用编辑
					listeners : {
						// 由于下拉框组件初始化赋值未触发change事件,因此手动赋值触发事件
						afterrender:function (self){
							for (var i = 0; i < relationConditionArr.length; i++) {
								var conditionName = relationConditionArr[i].name;
								var conditionType = relationConditionArr[i].xtype;
								var conditionValue = relationConditionArr[i].value;
								if (self.name === conditionName && self.xtype === conditionType){
									Ext.ComponentQuery.query(conditionType + '[name="' + conditionName + '"]')[0].setValue(conditionValue);
								}
							}
						},
						change : function(self, newValue, oldValue, eOpts) {
							var conditionPanel = Ext.ComponentQuery.query('form#condition')[0];
							conditionPanel.items.each(function(item, index, length) {
								if (item.srccode && item.name != self.name) {
									var srcFlag = false;
									var srcIds = item.srccode.split(',');
									for ( var i = 0; i < srcIds.length; i++) {
										if (self.name.trim() == srcIds[i].trim()) {
											srcFlag = true;
											break;
										}
									}
									if (srcFlag) {
										var xtype = item.xtype;
										var name = item.name;
										var target = Ext.ComponentQuery.query(xtype + '[name="' + name + '"]')[0];
										var targetValue = item.value;
										var linkValue = self.value;
										if (xtype == "treecombobox" || xtype == "combobox") {
											target.getStore().getProxy().extraParams[self.name.trim()] = linkValue;
											target.getStore().load({
												callback : function(records, operation, success) {
													if(records.length == 1){
	            			    			    		if (xtype == "treecombobox") {
															if(records[0].childNodes && records[0].childNodes.length > 0){
																target.setValue('');
															}else{
																target.setValue(records[0].get("code"));
															}
														}else{
															target.setValue(records[0].get("code"));
														}
	            			    			    	}else{
	            			    			    		if(xtype == "treecombobox"){
		            			    			    		//target.setValue('');
		            			    			    	}else{
		            			    			    		var dataFlag = false;
			            			    			    	for(var i=0;i<records.length;i++){
			            			    			    		var code = records[i].get("code");
			            			    			    		if(code == targetValue){
			            			    			    			dataFlag = true;
			            			    			    			break;
			            			    			    		}
			            			    			    	}
			            			    			    	if(dataFlag){
			            			    			    		target.setValue(targetValue);
			            			    			    	}else{
			            			    			    		target.setValue('');
			            			    			    	}
		            			    			    	}
	            			    			    	}
												}
											});
										} else if (xtype == "textfield") {
											target.setValue('');
											if (linkValue) {
												$.post('/getTextFieldValue', {
													q_id : tables_id,
													c_code : item.name,
													target : self.name.trim() + "#" + linkValue,
												}, function(data) {
													if (data.targetValue) {
														target.setValue(data.targetValue);
													}
												}, 'JSON');
											}
										}
									}
								}
							});
						}
					}
				});
			} else if ('textfield' == dispmode) {
				conditionItems.push({
					xtype : "textfield",
					fieldLabel : fieldtitle,
					name : fieldcode,
					value : value,
					hidden : hiddenFlag,
					srccode : srccode,
					margin : '2 5 2 6',
					padding : '0 0 0 0',
					emptyText : tips,
					allowBlank : isMustPut(ismust),
					enableKeyEvents : true,
					listeners : {
						'keydown' : function(self, e, eOpts) {
							var key = e.getKey();
							if (key == Ext.EventObject.ENTER) {
								reloadStore();
							}
						}
					}
				});
			} else if ('datefield' == dispmode) {
				conditionItems.push({
					xtype : "datefield",
					fieldLabel : fieldtitle,
					name : fieldcode,
					value : value,
					hidden : hiddenFlag,
					format : 'Y-m-d',
					margin : '2 5 2 6',
					padding : '0 0 0 0',
					emptyText : tips,
					allowBlank : isMustPut(ismust)
				});
			} else if ('label' == dispmode) {
				conditionItems.push({
					xtype : "textfield",
					fieldLabel : "附加条件",
					name : fieldcode,
					columnWidth : 0.64,
					editable : false,// 禁用编辑
					value : value,
					hidden : hiddenFlag,
					margin : '2 5 2 6',
					padding : '0 0 0 0'
				});
			} else if ('numberfield' == dispmode) {
				conditionItems.push({
					xtype : "numberfield",
					fieldLabel : fieldtitle,
					name : fieldcode,
					value : value,
					hidden : hiddenFlag,
					margin : '2 5 2 6',
					padding : '0 0 0 0',
					emptyText : tips,
					allowBlank : isMustPut(ismust)
				});
			}
		});
	}
	// 如果给下拉框组件新赋的值与初始化值一致,也不会触发change事件,因此在此处将有级联关系的父级初始化值置为空
	for (var i = 0; i < conditionItems.length; i++) {
		for (var j = 0; j < relationConditionArr.length; j++) {
			// 如果当前组件是级联父级并且类型是combobox(只有combobox初始化时需要手动触发change事件)
			if (conditionItems[i].name === relationConditionArr[j].name && relationConditionArr[j].xtype === "combobox"){
				conditionItems[i].value = "";
			}
		}
	}
	return conditionItems;
}

/**
 * 下拉框store配置
 *
 * @param model
 * @param cId
 * @param conditionIsRight
 * @param source
 * @returns
 */
function comboboxStore(model, cId, conditionIsRight, source) {
	if (source == null) {
		return EleStoreEnum(model);
	}
	return getQueryStrore(cId, {
		isRight : conditionIsRight
	});

}

/**
 * 下拉树是否只能选择子项配置
 *
 * @param isLeaf
 * @returns {String}
 */
function getLeafFlag(isLeaf) {
	var selectModel = 'all';
	if (isLeaf == 1) {
		selectModel = 'leaf';
	}
	return selectModel;
}

/**
 * 下拉树是否允许多选配置
 *
 * @param ismul
 * @returns {String}
 */
function getMulFlag(ismul) {
	var checkModel = 'single';
	if (ismul == 1) {
		checkModel = 'multi';
	}
	return checkModel;
}

/**
 * root是否可用
 *
 * @param ismul
 * @returns {Boolean}
 */
function getRootFlag(ismul) {
	var rootFlag = true;
	if (ismul == 0) {
		rootFlag = false;
	}
	return rootFlag;
}

/**
 * 是否必选
 *
 * @param ismust
 * @returns {Boolean}
 */
function isMustPut(ismust) {
	var flag = true;
	if ("1" == ismust) {
		flag = false;
	}
	return flag;
}

/**
 * 页签配置
 *
 * @param tablesList
 */
function tablePanelConf(tablesList){
	if(!isNull(tablesIsCover)){
		for(var i = 0; i < tablesIsCover.length; i++) {
			tablePanelItems.push({
				title: '<span title="' + tablesIsCover[i].title + '">' + tablesIsCover[i].title + '</span>',
				closable: false,
				layout: 'fit',
				xtype:"panel",
				html:'<iframe id="tablesCover'+i+'" src="' + tablesIsCover[i].url + '" '
					+'style="width:100%;height:100%;margin:0px auto;" frameborder="0"></iframe>'
			});
		}
	}
	for ( var i = 0; i < tablesList.length; i++) {
		sheetNameMap[tablesList[i].Q_ID] = tablesList[i].TABLES_SHEET_NAME;
		var classArr=classNameArray.filter(function (item,index) {
			return item.Q_ID==tablesList[i].Q_ID
		})
		var items=[]
		// 报表左上角添加报表批注
		if(tablesList[i].Q_NOTE){
			items[0]={
				xtype: 'panel',
				region: 'north',
				html: tablesList[i].Q_NOTE, // 表格的内容
				width: "100%", // DIV的宽度
				height: "50px", // DIV的高度
				ui: 'transparent',
				cls:"header-note-left",
			}
		}
		items.push({
			xtype: 'panel',
			region: 'center',
			layout: 'fit',
			border: false,
			flex:1,
			width: '100%',
			items: [initGrid(tablesList[i])]
		})
		tablePanelItems.push({
			title: '<span title="'+tablesList[i].TABLES_SHEET_NAME+'">'+tablesList[i].TABLES_SHEET_NAME+'</span>',
			q_note: tablesList[i].Q_NOTE,
			export_data_format: tablesList[i].EXPORT_DATA_FORMAT,
			closable: false,
            layout: 'vbox',
            xtype:"panel",
			cls:classArr[0]?classArr[0].CLASSNAME:"",
            itemId:'tabpable'+tablesList[i].Q_ID,
            // items:[initGrid(tablesList[i])]
			items:items
		});
	}
}

/**
 * 初始化右侧主表格
 */
function initGrid(record) {
	var columns = fieldConf(record.fieldList,record.Q_ID);
	titleMap[record.Q_ID] = record.Q_TITLE;
	printMap[record.Q_ID] = record.PRINT_CONFIG;
	var config={
            itemId: 'reportQueryGrid'+record.Q_ID,
            headerConfig: {
                headerJson: columns,
                columnCls: 'normal',// 查询报表支持表头换行
                columnAutoWidth: false
            },
            header:{
		    	xtype:'header',
		    	title:'<span class="header-font">'+record.Q_TITLE+'</span>',
		    	itemId:'condition_header'+record.Q_ID,
		    	baseCls:'x-panel-header-new',
		    	height: 40,
		    	titleAlign:'center',
		    	hidden:record.Q_IS_TITLE == "1" ? false : true,
		    	margin:'0 0 0 0',
	 	 		padding:'0 0 0 0',
	 	 		items:[{
	                xtype: 'tbspacer',
	                itemId:'report_query_sql',
	                width:100,
	                height:'100%',
	                listeners:{
	                    afterrender:function (self) {
	                    	if(sqlDebug == "1"){
	                    		$(self.el.dom).click( function () {
	                                // 弹出弹出框
	                                Ext.create('Ext.window.Window', {
	                                    title: '报表查询sql', // 窗口标题
	                                    width: 700, // 窗口宽度
	                                    height: 360, // 窗口高度
	                                    layout: 'fit',
	                                    maximizable: true,
	                                    itemId: 'window_notice_info', // 窗口标识
	                                    buttonAlign: 'right', // 按钮显示的位置
	                                    modal: true, // 模式窗口，弹出窗口后屏蔽掉其他组件
	                                    closeAction: 'destroy',// hide:单击关闭图标后隐藏，可以调用show()显示。如果是destroy，则会将window销毁。
	                                    items: [{
	                                        xtype: 'form',
	                                        width: '100%',
	                                        height: '100%',
	                                        itemId: 'window_querysql_panel',
	                                        layout: 'column',
	                                        autoScroll: true,
	                                        defaultType: 'textareafield',
	                                        defaults: {
	                                            margin: '5 10 5 10',
	                                            columnWidth: .99,
	                                            labelWidth: 94// 控件默认标签宽度
	                                        },
	                                        items: [
	                                            {
	                                                height:'95%',
	                                                value:querySql[record.Q_ID]

	                                            }
	                                        ]

	                                    }
	                                    ]

	                                }).show();
	                            });
	                    	}
	                    }
	                }
	            }]
		    },
            checkBox: false,
            rowNumber: true,
            border: true,
            autoLoad: false,
            width: '100%',
            flex: 1,
            dataUrl: '/sys-report/getGridData',
            remoteSort:true,
            sortableColumns:eval(sortableColumns),
            isLocalStorage:eval(isLocalStorage),
            enableLocking:eval(enableLocking),
            pageConfig: {
                enablePage: record.Q_IS_PAGE == "1" ? true:false,
                pageNum:true,
                pageSize:50
            },
		    viewConfig:{
    	        stripeRows:stripeRows,// 在表格中显示斑马线
				listeners: {
					refresh: function (view) {
						if(!!view.mergeCells) {
							view.mergeCells(view);
						}
					}
				}
    	    },
			listeners:{
				afterRender: function(grid, eOpts){
					// 处理合并单元格问题
					var mergeArray = [];
					function getMergeArray(columns) {
						for(var i = 0; !!columns && i < columns.length; i++) {
							if(!!columns[i].columns && columns[i].columns.length > 0) {
								getMergeArray(columns[i].columns);
							}else if("1" == columns[i].IS_MERGE) {
								mergeArray.push(columns[i]["FIELD_CODE"]);
							}
						}
					}
					getMergeArray(record.fieldList);
					var view = grid.getView(),
						store = grid.getStore();
					view.mergeCells = function (view) {
						var rows = [],
							colCount = view.getGridColumns().length,
							mergedCells = {},
							columns = view.getGridColumns();
						try{
							rows=grid.getView().getNodes()
						}catch(e){
							
						}
						for (var colIndex = 0; colIndex < colCount; colIndex++) {
							if(mergeArray.indexOf(columns[colIndex].dataIndex) == -1) {
								continue;
							}
							var rowIdx = 0,
								rowspan = 1,
								lastValue = '',
								lastCellHeight = 0,
								lastCellWidth = 0;
							while (rowIdx < rows.length) {
								var currentRow = rows[rowIdx],
									currentCell = Ext.get(currentRow).query('td')[colIndex],
									currentValue = currentCell.innerHTML;
								if (mergedCells[rowIdx] && mergedCells[rowIdx][colIndex]) {
									rowIdx++;
									continue;
								}
								if (currentValue === lastValue) {
									rowspan++;
									currentCell.innerHTML = '';
									var currentCellHeight = currentCell.offsetHeight;
									if (currentCellHeight > lastCellHeight) {
										lastCellHeight = currentCellHeight;
									}
									var currentCellWidth = currentCell.offsetWidth;
									if (currentCellWidth > lastCellWidth) {
										lastCellWidth = currentCellWidth;
									}
								} else {
									if (rowspan > 1) {
										var prevRow = rows[rowIdx - rowspan];
										if (!!Ext.get(prevRow)) {
											var prevCell = Ext.get(prevRow).query('td')[colIndex];
											prevCell.rowSpan = rowspan;
											var divHeight = (lastCellHeight) * rowspan;
											if(!!lastValue) {
												prevCell.innerHTML = '<div style="background-color:#FFF;width: '+ (lastCellWidth - 1) + 'px;line-height: ' + (divHeight - 9) + 'px;height: ' + (divHeight - 3) + 'px;position: absolute;">' + lastValue + '</div>';
											}
											for (var i = rowIdx - rowspan + 1; i < rowIdx; i++) {
												if (!mergedCells[i]) {
													mergedCells[i] = {};
												}
												mergedCells[i][colIndex] = true;
											}
										}
									}
									lastValue = currentValue;
									rowspan = 1;
									lastCellHeight = currentCell.offsetHeight;
									lastCellWidth = currentCell.offsetWidth;
								}
								rowIdx++;
							}

							if (rowspan > 1) {
								var prevRow = rows[rowIdx - rowspan];
								if (!!Ext.get(prevRow)) {
									var prevCell = Ext.get(prevRow).query('td')[colIndex];
									prevCell.rowSpan = rowspan;
									var divHeight = (lastCellHeight) * rowspan;
									if(!!lastValue) {
										prevCell.innerHTML = '<div style="background-color:#FFF;width: '+ (lastCellWidth - 1) + 'px;line-height: ' + (divHeight - 9) + 'px;height: ' + (divHeight - 3) + 'px;position: absolute;">' + lastValue + '</div>';
									}
									for (var i = rowIdx - rowspan + 1; i < rowIdx; i++) {
										if (!mergedCells[i]) {
											mergedCells[i] = {};
										}
										mergedCells[i][colIndex] = true;
									}
								}
							}
						}
					};
					store.on('load', function () {
						view.mergeCells(view);
					});
					grid.on('refresh', function () {
						view.mergeCells(view);
					})
					// 处理多表头错行问题
					Ext.defer(function() {
						var aView = grid.getView();
						var childrenNode=null;
						var Nodedom=[]
						try{
							var childrenNode=aView.headerCt.container.dom.childNodes[2].children;
							Nodedom = childrenNode[0].children[0].children;
						}catch (e) {
							var childrenNode=aView.normalGrid.container.dom.childNodes;
							var lockedColumns=childrenNode[0].childNodes[0].childNodes[0].childNodes[0].childNodes;
							var normalColumns=childrenNode[1].childNodes[0].childNodes[0].childNodes[0].childNodes;
							Nodedom.push.apply(Nodedom, lockedColumns);
							Nodedom.push.apply(Nodedom, normalColumns);
						}
						tableHeaderRowsNum=1;
						for(var i=0;i<Nodedom.length;i++){
							if(Nodedom[i].children&&Nodedom[i].children.length>1){
								getTableHeaderRows(Nodedom[i].children,1)
							}
						}


						tableHeaderMap={}
						for(var i=0;i<Nodedom.length;i++){
							if(Nodedom[i].children&&Nodedom[i].children.length>1){
								getTableColumnHeight(Nodedom[i].children,1)
							}
						}
						if(tableHeaderMap&&JSON.stringify(tableHeaderMap)!="{}"){
							var allHeight=0;
							for(var k in tableHeaderMap){
								allHeight += tableHeaderMap[k]
							}
							for(var i=0;i<Nodedom.length;i++){
								if(Nodedom[i].childElementCount==1){
									$(Nodedom[i]).height(allHeight-14+"px");
								}else{
									setTableColumnHeight(Nodedom[i].children,1)
								}
							}
							grid.updateLayout()
						}
					}, 100, this);
            	}
			}
        };
	if(record.Q_IS_SUM == 1){
		config.features = [{
      	   ftype: 'summary',
      	   remoteRoot: 'summary',
      	   dock: 'top',
         }];
	}

	if(record.MONEY_UNIT !=0){
		config.tbar=[
		  '->', '->','->','->', '->','->','->',
         {xtype: "label" ,text: "金额单位：" ,width:65},
         {
         	 xtype:'form',
         	 padding:'0 0 0 0',
         	 width:70,
         	 layout:'fit',
         	 border:false,
         	 items:[{
            		 xtype:"combobox",
            		 name:"unitSelect"+record.Q_ID,
            		 margin:'0 0 0 0',
            		 store: unitStore,
            		 queryMode: 'local',
            		 editable: false,
            		 allowBlank:false,
            		 value : record.MONEY_UNIT,
	            	 displayField: 'name',
	            	 valueField: 'abbr',
	            	 listeners:{
					    	/*
							 * change : function( self, newValue, oldValue,
							 * eOpts ){ reloadStore(); },
							 */
					    	select:function ( combo, data, eOpts ){
					    		// unit = record.get("abbr");
					    		reloadGrid(record.Q_ID,combo.getValue());
					    	}
					    }
               	}]
          }
     	];
	}
	//CLASSNAME为report-tables-divider，report-tables-no-divider，report-tables-bottom-border 表格底部添加套表说明作为注释
	var classArr=classNameArray.filter(function (item,index) {
		return item.Q_ID==record.Q_ID
	})
	var customClassArr=['report-tables-divider','report-tables-no-divider','report-tables-bottom-border']
	if(record.Q_REMARK&&classArr[0]&&classArr[0].CLASSNAME&&customClassArr.includes(classArr[0].CLASSNAME)){
		config.bbar= {
			xtype: 'toolbar',
			cls:"default-hide-bottom-toolbar",
			items: [{
				xtype: 'tbtext',
				text: '注：'+record.Q_REMARK
			}]
		}
	}
	var dataGrid = DSYGrid.createGrid(config);
    return dataGrid;
}

/***
 * 获取每个表格的表头的行数
 */
function getTableHeaderRows(dom,objName){
	if(Number(objName)>tableHeaderRowsNum){
		tableHeaderRowsNum=Number(objName)
	}
	var flag=true;
	for(var i=0;i<dom.length;i++){
		var ele=dom[i].children[0].children;
		if(ele&&ele.length>1){
			for(var j=0;j<ele.length;j++){
				if(ele[j].children&&ele[j].children.length>1){
					flag=false;
					getTableHeaderRows(ele[j].children,Number(objName)+1)
				}
			}
			
			
		}
	}
	if(flag){
		for(var j=0;j<ele.length;j++){
			if(Number(objName)+1>tableHeaderRowsNum){
				tableHeaderRowsNum=Number(objName)+1
			}
		}
	}
}
/***
 * 获取表格的每个表头的高度
 */
function getTableColumnHeight(dom,objName){
	if(dom[0]&&dom[0].children.length==1){
		if(tableHeaderMap[objName]&&tableHeaderMap[objName]<dom[0].clientHeight){
			tableHeaderMap[objName]=dom[0].clientHeight
		}else if(!tableHeaderMap[objName]){
			tableHeaderMap[objName]=dom[0].clientHeight
		}
	}
	var flag=true;
	for(var i=0;i<dom.length;i++){
		var ele=dom[i].children[0].children;
		if(ele&&ele.length>1){
			for(var j=0;j<ele.length;j++){
				if(ele[j].children&&ele[j].children.length>1){
					flag=false;
					getTableColumnHeight(ele[j].children,Number(objName)+1)
				}
			}
			
			
		}
	}
	var num=Number(objName)+1
	if(flag&&num==tableHeaderRowsNum){
		for(var j=0;j<ele.length;j++){
			if(!tableHeaderMap[num]){
				tableHeaderMap[num]=ele[j].children[0].clientHeight
			}
		}
	}
}
/*****
 * 通过获取的最大高度，设置每一行的最大高度
 */
function setTableColumnHeight(Nodedom,objName){
	var innerHeight=tableHeaderMap[objName]-14+"px"
	if(Nodedom[0]&&Nodedom[0].children.length==1){
		$(Nodedom[0]).height(innerHeight)
	}
	for(var i=0;i<Nodedom.length;i++){
		var ele=Nodedom[i].children[0].children;
		if(ele&&ele.length>1){
			var flag=true;
			for(var j=0;j<ele.length;j++){
				if(ele[j].children&&ele[j].children.length>1){
					flag=false;
					setTableColumnHeight(ele[j].children,Number(objName)+1)
				}
			}
			if(flag){
				var num=Number(objName)+1
				var allHeight=0;
				for(var k in tableHeaderMap){
					if(num<=k){
						allHeight += tableHeaderMap[k]
					}
				}
				for(var j=0;j<ele.length;j++){
					$(ele[j].children[0]).height(allHeight-14+"px")
				}
			}
			
		}else{
			$(Nodedom[i]).height(innerHeight)
		}
	}
}
/**
 * 表头配置
 *
 * @param colArray
 * @returns {Array}
 */
function fieldConf(colArray,qid){
	if (colArray == null || colArray.length <= 0) {
		return new Array();
	}
	deepMap[qid] = 1;
	var columns = new Array();
	var col_length=colArray.length;
	var i = 0;
	if(rownumberer){
		// 如果显示行号,第一列设置为rownumberer
		col_length++;
		i++;
		columns[0]={
	         xtype: 'rownumberer',
			 dataIndex:'rownumberer',
			 header:'',
			 text:'',
			 align: 'center',
	         width:50,
	         summaryType: 'count',
	         summaryRenderer: function () {
	             return '合计';
	         }
        };
		for ( ; i < col_length; i++) {
			var deepcount = 1;
			// 列显示行号
			var col=colArray[i-1];
			columns[i] = configColumn(col);
			if(col.columns && col.columns.length > 0){
				childColumns(columns[i],col.columns,deepcount,qid);
			}
		}
	}else{
		for ( ; i < col_length; i++) {
			var deepcount = 1;
			// 列显示行号
			var col=colArray[i];
			columns[i] = configColumn(col);
			if(col.columns && col.columns.length > 0){
				childColumns(columns[i],col.columns,deepcount,qid);
			}
		}
	}
	return columns;
}

/**
 * 递归牌子标题
 *
 * @param rootColumn
 * @param childColumns
 * @param deepcount
 */
function childColumns(rootColumn,childColumns,deepcount,qid){
	deepcount++;
	var child = new Array();
	for(var i = 0;i<childColumns.length;i++){
		child[i] =  configColumn(childColumns[i]);
		if(childColumns[i].columns && childColumns[i].columns.length > 0){
			arguments.callee(child[i],childColumns[i].columns,deepcount,qid);
		}else{
			if(deepcount > deepMap[qid]){
				deepMap[qid] = deepcount;
			}
		}
	}
	rootColumn.columns=child;
}

/**
* 配置表头
*/
function configColumn(col){
	var column = {};
	var customClass="";
	if(col.FIELD_TITLE==""){
		customClass="column-no-top-border"
	}
	if(col.columns&&col.columns.length>0){
		var isShowChild=true;
		col.columns.forEach(function(item,index){
			if(item.FIELD_TITLE){
				isShowChild=false;
			}
		})
		if(isShowChild){
			customClass=customClass+" column-hidden-child"
		}
	}
	column = {
		header : col.FIELD_TITLE,// 设置标题文字
		is_merge : col.IS_MERGE,// 设置表头合并单元格
		type : col.FIELD_TYPE == null ? "string" : col.FIELD_TYPE, // 设置列解析类型
		text : col.FIELD_TITLE,// 设置标题文字
		dataIndex : col.FIELD_CODE,// 设置列字段
		hidden:col.IS_SHOW == "0"?true:false,
		cls:customClass
	};
	column.width = parseInt(col.FIELD_LENGTH) == 0 ? 100 : parseInt(col.FIELD_LENGTH);// 设置固定列宽;
	column.style = '{text-align: center;}';
	column.summaryRenderer= function (value,data,dataIndex) {
        return value;
    };
	// 默认列渲染类型为字符型 设置列渲染类型为数字型，右对齐
	if (col.FIELD_TYPE == "int" || col.fieldType=="number") {
		column.align = "right";
		column.xtype = "numbercolumn";
		column.summaryType = "sum";
		column.format = "0";
		column.summaryRenderer= function (value,data,dataIndex) {
			return Ext.util.Format.number(value, '0,000');
        };
	}else if(col.FIELD_TYPE == "float"){
		var field_format = col.FIELD_FORMAT;
		column.align = "right";
		column.xtype = "numbercolumn";
		if(!isNull(field_format)){
			column.format = field_format;
		}
		column.summaryType = "sum";
		column.summaryRenderer= function (value,data,dataIndex) {
			if(!isNull(field_format)){
				return Ext.util.Format.number(value, field_format);
			}else{
				return Ext.util.Format.number(value, '0,000.00');
			}
        };
	}else if(col.FIELD_TYPE == "rstring"){
		column.type = "string";
		column.align = "right";
	}else if (col.FIELD_TYPE == "numberstr"){
		column.align = "right";
		column.type = "string";
		column.summaryType = "sum";
		if (!isNull(col.FIELD_FORMAT)) {
			column.format = col.FIELD_FORMAT;
		}
		column.summaryRenderer= function (value,data,dataIndex) {
			if (!isNull(col.FIELD_FORMAT)) {
				return Ext.util.Format.number(value, col.FIELD_FORMAT);
			} else {
				return Ext.util.Format.number(value, '0,000.##');
			}
		};
	}
	if(col.FIELD_CODE){
		if((col.FIELD_CODE.toUpperCase()) == 'BUSIID'){
			column.align = "center";
		}
	}
	if(col.IS_LOCK == 1){
		column.locked = true;
	}
	if(col.IS_NEWLINE == 1){
		column.cellWrap = true;
	}
	if(col.IS_URL_PARAM == 1){
		urlParam.push(col.FIELD_CODE);
	}
	if(col.DATA_URL != null||col.DATA_URL_FIELD != null){
    	if(col.DATA_URL_FIELD != null){
    		url_field[col.FIELD_CODE]=col.DATA_URL_FIELD;
    	}else{
    		if(col.DATA_URL != null){
    			url[col.FIELD_CODE]=col.DATA_URL;
    		}
    	}
		urlType[col.FIELD_CODE]=col.URL_TYPE;
	}
	if(col.DATA_URL != null ||col.IS_NEWLINE == 1||col.DATA_URL_FIELD != null){
		column.renderer= function (value, cell,record, rowIndex, colIndex, store, view) {
			var headerCt = this.getHeaderContainer(),
			column = headerCt.getHeaderAtIndex(colIndex),
			colname=column.dataIndex;
     		if(url[colname] == null&&url_field[colname]==null){
     			return value;
     		}
			if(url[colname] != null||url_field[colname] != null){
				var cururl;
			    if(url_field[colname] != null){
			    	var urlfield = url_field[colname];
			    	cururl = record.get(urlfield);
			    }else{
			    	cururl = url[colname];
			    }
			    if(cururl == null|| ""==cururl){
			    	return value;
			    }
			    if(cururl.indexOf("?")>0){
    			    cururl = cururl + "&";
     	        }else{
     	            cururl = cururl+"?";
     	        }
    			var tran = "";
    			for(var i in  urlParam){
    				if(""==tran){
    					if(urlParam[i].toUpperCase() == 'BUSIID'){
    						if(record.get(urlParam[i].toUpperCase()) != null && record.get(urlParam[i].toUpperCase()) != ""){
    							var bus = record.get(urlParam[i].toUpperCase()).split('-');
    			    			tran = urlParam[i]+"=" + bus[0];
    			    		}
    			    	}else{
    			    		tran = urlParam[i]+"=" + record.get(urlParam[i].toUpperCase());
    			    	}
    	 	 	   	}else{
	    	 	 		if(urlParam[i].toUpperCase() == 'BUSIID'){
	    			    	if(record.get(urlParam[i].toUpperCase()) != null && record.get(urlParam[i].toUpperCase()) != ""){
	    			    		var bus = record.get(urlParam[i].toUpperCase()).split('-');
	    			    		tran = tran+"&"+urlParam[i]+"=" + bus[0];
	    			    	}
	    	 	 		}else{
	    	 	 			tran = tran+"&"+urlParam[i]+"=" + record.get(urlParam[i].toUpperCase());
	    	 	 		}
    	 	 	   	}
    			}
				//去掉传参的双引号
				tran = tran.replaceAll('"','');
    			if((colname.toUpperCase()) == 'BUSIID'){
    				if(value == null|| value == ""){
    			    	return value;
    			    }else{
    			    	var values = value.split('-');
    			    	var showValue = values[1];
    			    	if(showValue == 1){
    			    		showValue = "";
    			    	}
    			    	return '<a href = "#" onclick ="showwindows(\''+cururl +tran+'\')"><img src="/report/image/sysbutton/fujian.png" width="13px" height="11px" title="查看附件"  />'+showValue+'</a>';
    			    }
    			}
    			if(urlType[colname]==1){
    				return '<a href = "#" onclick ="showwindows(\''+cururl +tran+'\')">' + value + '</a>';
    			}else{
    				return '<a href = "#" onclick ="menuOnClick(\''+col.FIELD_TITLE+'穿透\',\''+cururl +tran+'\')">' + value + '</a>';
    			}
			}
		};
	}else{
		column.renderer= function (value, cell,record, rowIndex, colIndex, store, view) {
			if(col.FIELD_TYPE == "string" || col.FIELD_TYPE == "rstring"){
				if(value){
					value = value.replace(/\s/g, "&nbsp;");
				}
			}else if (col.FIELD_TYPE == "int" || col.fieldType=="number"){
				value = Ext.util.Format.number(value, '0,000');
			}else if(col.FIELD_TYPE == "float"){
				if(!isNull(col.FIELD_FORMAT)){
					value = Ext.util.Format.number(value, col.FIELD_FORMAT);
				}else{
					value = Ext.util.Format.number(value, '0,000.00');
				}
			}else if (col.FIELD_TYPE == "numberstr"){
				value = Ext.util.Format.number(value, '0,000.##');
			}
			return value;
		};
	}
	return column;
}

/**
 * 查询数据
 */
function reloadStore(){
	Ext.ComponentQuery.query('button#report_query_search')[0].setDisabled(true);
	var form = Ext.ComponentQuery.query('form#condition')[0];
    if (!form.isValid()){
    	// saveLog(q_title,'BUTTON',q_title+'未执行查询，存在隐藏必录条件！');
    	Ext.ComponentQuery.query('button#report_query_search')[0].setDisabled(false);
    	return;
    }
    var formData = form.getForm().getFieldValues();
    formData = $.extend({}, formData, form.getValues());
    var new_params =  form.getValues();
    if(!isNull(tablesIsCover)){
    	for(var i = 0; i < tablesIsCover.length; i++) {
    		$("#tablesCover"+i).attr("src", tablesIsCover[i].url);
		}
    	
    }
    titleMap = {};
    for ( var i = 0; i < qidList.length; i++) {
    	var queryMap = {};
    	Ext.Ajax.request({
    		method : 'POST',
    		url : "/sys-report/getReportQueryHeader",
    		params : {
    			code:qidList[i],
    			detailForm: encode64(Ext.util.JSON.encode([formData]))
    		},
    		async : false,
    		success : function(response, options) {
    			// 获取返回的JSON，并根据gridid，获取表头配置信息
    			var respText = Ext.util.JSON.decode(response.responseText);
    			queryMap = eval(respText.queryMap);
    		},
    		failure : function(response, options) {
    			Ext.MessageBox.minWidth = 120;
    			Ext.Msg.alert('提示', '获取报表头信息失败！');
    		}
    	});
    	var unitPanel = Ext.ComponentQuery.query('combobox[name="unitSelect' + qidList[i] + '"]')[0];
    	var unitValue = 1;
    	if(unitPanel){
    		unitValue = unitPanel.getValue();
    		queryMap["MONEY_UNIT"] = unitValue;
    	}
    	var tabGridPanel = Ext.ComponentQuery.query('panel#tabpable'+qidList[i])[0];
		var gridComponent = tabGridPanel.down('grid'); // 假设表格组件为Grid，可以根据实际情况修改
		var parentPanel=gridComponent.up()
		if (gridComponent) {
			gridComponent.destroy();
			tabGridPanel.remove(parentPanel);
		}
    	// tabGridPanel.removeAll(true);
    	tabGridPanel.add(initGrid(queryMap));
    	var reportGrid = DSYGrid.getGrid('reportQueryGrid'+qidList[i]);
    	var store = reportGrid.getStore();
    	store.getProxy().extraParams["unit"] = unitValue;
    	store.getProxy().extraParams["q_id"] = qidList[i];
    	store.getProxy().extraParams["tables_id"] = tables_id;
    	store.getProxy().extraParams["condition"] = q_select_condition;
        store.getProxy().extraParams["rownumberer"] = rownumberer;
    	Ext.apply(store.proxy.extraParams, new_params);
    	var startD = new Date();
    	store.loadPage(1,{
    	    callback: function(records, operation, success) {
    	    	var message=Ext.util.JSON.decode(operation['_response'].responseText).message;
    	    	if(message){
    	    		Ext.Msg.alert('提示', message);
    	    	}else{
    	    		var qId = Ext.util.JSON.decode(operation['_response'].responseText).qId;
    	    		querySql[qId]=Ext.util.JSON.decode(operation['_response'].responseText).sql;
    		    	if(querySql[qId] && querySql[qId].indexOf('sql错误') > 0){
    		    		var endD = new Date();
    		    		var useD = (endD.getTime()-startD.getTime())/1000;
    		    		useD = numberFormat(useD,2,1);
    		    		// saveLog(q_title,'BUTTON',q_title+'报表查询失败，耗时：'+useD+"秒");
    		    	}else{
    		    		var endD = new Date();
    		    		var useD = (endD.getTime()-startD.getTime())/1000;
    		    		useD = numberFormat(useD,2,1);
    		    		// saveLog(q_title,'BUTTON',q_title+'报表查询成功，耗时：'+useD+"秒");
    		    	}
    		    	var totalcount = parseInt(Ext.util.JSON.decode(operation['_response'].responseText).totalcount);
    		    	var store = DSYGrid.getGrid('reportQueryGrid'+qId).getStore();
    		    	if(!!!orderCheck){
    		    		orderCheck = 100000;
    		    	}
    		    	if(totalcount > orderCheck){
    		    		store.setRemoteSort(false);
    		    	}else{
    		    		store.setRemoteSort(true);
    		    	}
    	    	}
    	    }
    	});
	}
    Ext.ComponentQuery.query('button[name="export"]')[0].setDisabled(false);
    Ext.ComponentQuery.query('button[name="print"]')[0].setDisabled(false);
    Ext.ComponentQuery.query('button#report_query_search')[0].setDisabled(false);
}


/**
 * 单个grid查询
 *
 * @param qid
 * @param unitValue
 */
function reloadGrid(qid,unitValue){
	var form = Ext.ComponentQuery.query('form#condition')[0];
    if (!form.isValid()){
    	// saveLog(q_title,'BUTTON',q_title+'未执行查询，存在隐藏必录条件！');
    	Ext.ComponentQuery.query('button#report_query_search')[0].setDisabled(false);
    	return;
    }
    var formData = form.getForm().getFieldValues();
    formData = $.extend({}, formData, form.getValues());
    var queryMap = {};
	Ext.Ajax.request({
		method : 'POST',
		url : "/sys-report/getReportQueryHeader",
		params : {
			code:qid,
			detailForm: encode64(Ext.util.JSON.encode([formData]))
		},
		async : false,
		success : function(response, options) {
			// 获取返回的JSON，并根据gridid，获取表头配置信息
			var respText = Ext.util.JSON.decode(response.responseText);
			queryMap = eval(respText.queryMap);
			queryMap.MONEY_UNIT=unitValue;

		},
		failure : function(response, options) {
			Ext.MessageBox.minWidth = 120;
			Ext.Msg.alert('提示', '获取报表头信息失败！');
		}
	});
	var tabGridPanel = Ext.ComponentQuery.query('panel#tabpable'+qid)[0];
	var gridComponent = tabGridPanel.down('grid'); 
	var parentPanel=gridComponent.up()
	if (gridComponent) {
		gridComponent.destroy();
		tabGridPanel.remove(parentPanel);
	}
	// tabGridPanel.removeAll(true);
	tabGridPanel.add(initGrid(queryMap));
	var reportGrid = DSYGrid.getGrid('reportQueryGrid'+qid);
    var store = reportGrid.getStore();
    store.getProxy().extraParams["unit"] = unitValue;
    store.getProxy().extraParams["condition"] = q_select_condition;
    store.getProxy().extraParams["q_id"] = qid;
    store.getProxy().extraParams["tables_id"] = tables_id;
    store.getProxy().extraParams["rownumberer"] = rownumberer;
    var new_params =  form.getValues();
	Ext.apply(store.proxy.extraParams, new_params);
	store.loadPage(1,{
	    callback: function(records, operation, success) {
	    	var message=Ext.util.JSON.decode(operation['_response'].responseText).message;
	    	if(message){
	    		Ext.Msg.alert('提示', message);
	    	}else{
	    		var qId = Ext.util.JSON.decode(operation['_response'].responseText).qId;
	    		querySql[qId]=Ext.util.JSON.decode(operation['_response'].responseText).sql;
	    		var totalcount = parseInt(Ext.util.JSON.decode(operation['_response'].responseText).totalcount);
		    	var store = DSYGrid.getGrid('reportQueryGrid'+qId).getStore();
		    	if(!!!orderCheck){
		    		orderCheck = 100000;
		    	}
		    	if(totalcount > orderCheck){
		    		store.setRemoteSort(false);
		    	}else{
		    		store.setRemoteSort(true);
		    	}
	    	}
	    }
	});
	Ext.ComponentQuery.query('button[name="export"]')[0].setDisabled(false);
}

/**
 * 表头、条件区域伸缩
 */
function toggleTopHidden() {
	for ( var i = 0; i < qidList.length; i++) {
		var conditionHeader = Ext.ComponentQuery.query('header#condition_header'+qidList[i])[0];
		if(upFlag){
			if(conditionHeader){
				conditionHeader.setHidden(true);
			}
	    }else{
	    	if(conditionHeader){
				conditionHeader.setHidden(false);
			}
	    }
	}
	var conditionPanel = Ext.ComponentQuery.query('form#condition')[0];
	if(upFlag){
    	if(conditionPanel){
    		conditionPanel.setHidden(true);
    	}
    	upFlag = false;
    	$('img.img-collapsible').attr('src', '/report/image/sysbutton/down.png');
    }else{
    	if(conditionPanel){
    		conditionPanel.setHidden(false);
    	}
    	upFlag = true;
    	$('img.img-collapsible').attr('src', '/report/image/sysbutton/up.png');
    }
}

/**
* 获取条件区参数
*/
function getConditionValues(){
	var form = Ext.ComponentQuery.query('form#condition')[0];
	var formData = form.getForm().getFieldValues();
    formData = $.extend({}, formData, form.getValues());
    return formData;
}




